/**
 * package: services
 * author: zhaiyujin
 * description:
 */
package services

import (
	"errors"
	"fmt"
	"github.com/kataras/iris/v12"
	"huanteng/vendors/validator"
	"huanteng/web/models"
	"huanteng/web/repositories"
)



type RoleService struct {
	repo  *repositories.RoleRepository
	rm  *repositories.RoleMenuRepository

}



/*func NewRoleService (repo repositories.RoleRepository) RoleService{
	return &RoleService{
		repo:repo,
	}
}*/
//删除数据
func (a *RoleService) Delete(ctx iris.Context)error  {
	var ids []uint
	ctx.ReadJSON(&ids)
	err:=a.repo.Delete(ids)
	if err!=nil{
		return err
	}
	//操作casbin角色
	go repositories.CsbinDeleteRole(ids)
	return nil
}


//所有角色
func (a *RoleService) AllRole() []models.Role{

   return a.repo.AllRole()

}

//所有角色,菜单列
/*func (a *RoleService) GetMenuByRole(id uint) []models.Role{

	return a.repo.AllRole()

}
*/

func (a *RoleService)Update(ctx iris.Context)(err error) {
	role:= models.Role{}
    err=validator.ValidateInfo(ctx.ReadJSON(&role))
	if err!=nil{
		return
	}
	a.repo.Update(&role)
	return nil
}
func (a *RoleService)RoleList(ctx iris.Context){

	a.repo.RoleList(ctx)

}

func (a *RoleService)GetByid(id uint) models.Role{
	return a.repo.GetByid(id)
}


func (a *RoleService)Create(ctx iris.Context) (models.Role, error)  {
	model:=models.Role{}
	err:=validator.ValidateInfo(ctx.ReadJSON(&model))
	if err!=nil{
		return model,err
	}
	role:=a.repo.FindByName(model.Name)
     if role.ID!=0{
     err=errors.New("角色名称已经存在了");
     	return model,err
	 }


	a.repo.Create(&model)

	return model,nil
}


//设置角色权限
func (s *RoleService)RoleSetMenu(id uint,ctx iris.Context) error {
	var menuids []uint
	err:=ctx.ReadJSON(&menuids)
	if err!=nil{
		return err
	}

	err=s.rm.SetRoleMenus(id,menuids)
	if err!=nil{
		return err
	}
	go repositories.CsbinSetRolePermission(id)
	return nil

}

func (a *RoleService)GetMenuById(id uint)[]uint  {
	 menuIDList:=[]uint{}
	a.repo.GetMenuById(models.RoleMenu{},models.RoleMenu{RoleID:id},&menuIDList,"menu_id")
	 return menuIDList
}


func (a *RoleService)SetRole(id uint,ctx iris.Context) error {
	var ids []uint
	err:=ctx.ReadJSON(&ids)
	if err!=nil{
		return err
	}
	err=a.repo.SetRole(id,ids)
	if err!=nil{
		return err
	}
	go repositories.CsbinAddRoleForUser(id)
	return nil
}


func(s *RoleService) Test()  {
	fmt.Println("fuck ouyang")
}
